<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use app\user\model\UserModel;
use cmf\controller\HomeBaseController;
use think\Validate;

class LoginController extends HomeBaseController
{

    /**
     * 登录
     */
    public function index()
    {
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);
        if (cmf_is_user_login()) {
            // 已经登录时直接跳到首页
            return redirect($this->request->root() . '/');
        } else {
            return $this->fetch(":login");
        }
    }

    /**
     * 登录验证提交
     */
    public function doLogin()
    {
        if ($this->request->isPost()) {

            // if (!cmf_captcha_check($data['captcha'])) {
            // $this->error(lang('CAPTCHA_NOT_RIGHT'));
            // }

            $userModel = new UserModel();
//             if (Validate::is($data['username'], 'email')) {
            //                 $user['user_email'] = $data['username'];
            //                 $log = $userModel->doEmail($user);
            //             } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            //                 $user['mobile'] = $data['username'];
            //                 $log = $userModel->doMobile($user);
            //             } else {
            //                 $user['user_login'] = $data['username'];
            //                 $log = $userModel->doName($user);
            //             }

            $data = $this->request->post();

            if ($data['reg_type'] == 1) {
                $validate = new Validate([
                    'code' => 'require',
                ]);
                $validate->message([
                    'code.require' => '用户名不能为空',
                ]);

                if (!$validate->check($data)) {
                    return json_encode(['status' => false, 'msg' => $validate->getError()]);
                }
                $log = $userModel->doWeixin($data['code'], $data['user']);
            } elseif ($data['reg_type'] == 2) {
                if (!preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
                    return json_encode(['status' => false, 'msg' => '电话号码不合规则']);
                }

                $validate = new Validate([
                    'username' => 'require',
                    'password' => 'require|min:6|max:32',
                ]);
                $validate->message([
                    'username.require' => '用户名不能为空',
                    'password.require' => '密码不能为空',
                    'password.max' => '密码不能超过32个字符',
                    'password.min' => '密码不能小于6个字符',
                ]);

                if (!$validate->check($data)) {
                    return json_encode(['status' => false, 'msg' => $validate->getError()]);
                }
                $user['mobile'] = $data['username'];
                $user['user_pass'] = $data['password'];
                $log = $userModel->doMobile($user);
            } else {
                // $user['user_login'] = $data['username'];
                // $log = $userModel->doName($user);
                return json_encode(['status' => false, 'msg' => '请求出错']);
            }

            // $session_login_http_referer = session('login_http_referer');
            // $redirect = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            // return json_encode($log);
            return $log;
        } else {
//             $this->error("请求错误");
            return json_encode(['status' => false, 'msg' => '请求错误']);
        }
    }

    /**
     * 找回密码
     */
    public function findPassword()
    {
        return $this->fetch('/find_password');
    }

    /**
     * 用户密码重置
     */
    public function passwordReset()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'mobile' => 'require',
                'verification_code' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'verification_code.require' => '验证码不能为空',
                'password.require' => '密码不能为空',
                'password.max' => '密码不能超过32个字符',
                'password.min' => '密码不能小于6个字符',
                'mobile.require' => '手机号不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                return json_encode(['status' => false, 'msg' => $validate->getError()]);
            }

            // $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
            // if (! cmf_captcha_check($data['captcha'], $captchaId)) {
            //     $this->error('验证码错误');
            // }

            $errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
            if (!empty($errMsg)) {
                return json_encode(['status' => false, 'msg' => $errMsg]);
            }

            $userModel = new UserModel();
            // if ($validate::is($data['username'], 'email')) {
            //     $log = $userModel->emailPasswordReset($data['username'], $data['password']);
            // } elseif (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            //     $user['mobile'] = $data['username'];
            //     $log = $userModel->mobilePasswordReset($data['username'], $data['password']);
            // } else {
            //     $log = 2;
            // }
            if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['mobile'])) {
                $log = $userModel->mobilePasswordReset($data['mobile'], $data['password']);
            } else {
                $log = 2;
            }

            switch ($log) {
                case 0:
                    return json_encode(['status' => true, 'msg' => "密码重置成功"]);
                    break;
                case 1:
                    return json_encode(['status' => false, 'msg' => "您的账户尚未注册"]);
                    break;
                case 2:
                    return json_encode(['status' => false, 'msg' => "您输入的账号格式错误"]);
                    break;
                default:
                    return json_encode(['status' => false, 'msg' => "未受理的请求"]);
            }
        } else {
            return json_encode(['status' => false, 'msg' => "请求错误"]);
        }
    }

    public function sendPhoneNumber()
    {
        $phone = $this->request->param("phone", '', "string");
        $code = $this->getrand();
        return json_encode(['status' => true, 'data' => $code, 'msg' => '发送成功']);
    }

    public function getrand()
    {
        $code = "";
        for ($i = 0; $i < 4; $i++) {
            $code .= rand(0, 9);
        }
        return $code;
    }

    public function testcount()
    {
        $userModel = new UserModel();
        $regtime = date("Ymd", time());
        $count_today = $userModel->where(["FROM_UNIXTIME(create_time,'%Y%m%d')" => $regtime])->count();
        $count_today += 1;
        $count_today = str_pad('1', 4, '0', STR_PAD_LEFT);
        echo $count_today;
        die;
    }
}
